﻿$(document).ready(function () {

    /*- select-city__link -*/
    $('.select-city__link').click(function (e) {

        if ($(this).parent().hasClass('selected')) {
            $(this).parent().removeClass('selected');
        } else {
            $(this).parent().addClass('selected');
        }
    });

    /*- contact-info -*/
    $('.contact-info address').click(function (e) {

        if ($(this).parent().hasClass('selected')) {
            $(this).parent().removeClass('selected');
        } else {
            $(this).parent().addClass('selected');
        }
    });

    /*- shopping-cart -*/
    $('.shopping-cart__link').click(function (e) {

        if ($(this).parent().hasClass('selected')) {
            $(this).parent().removeClass('selected');
        } else {
            showBasket();
            $(this).parent().addClass('selected');
        }
    });

    /*- drop-down-menu -*/
    $('.drop-down-menu__title').click(function (e) {

        if ($(this).parent().hasClass('selected')) {
            $(this).parent().removeClass('selected');
        } else {
            $(this).parent().addClass('selected');
        }
    });

    /*- drop-down-menu__list__tabs -*/
    $(function () {
        $('.drop-down-menu__list__tabs__title').click(function () {
            $(this)
                    .siblings().removeClass('selected').end()
                    .next('.drop-down-menu__list__tabs__content').andSelf().addClass('selected');
        });
    });

    /*- drop-down-menu__list -*/
    $('.drop-down-menu__list__link').click(function (e) {

        if ($(this).parent().hasClass('selected')) {
            $(this).parent().removeClass('selected');
        } else {
            $('.drop-down-menu__list__item').removeClass('selected');
            $(this).parent().addClass('selected');
        }
        return false;
    });

    /*- info-tabs -*/
    $(function () {
        $('.info-tabs__title').click(function () {
            $(this)
                    .siblings().removeClass('selected').end()
                    .next('.info-tabs__content').andSelf().addClass('selected');
        });
    });

    /*- goods-tabs -*/
    $(function () {
        $('.goods-tabs__title').click(function () {
            $(this)
                    .siblings().removeClass('selected').end()
                    .next('.goods-tabs__content').andSelf().addClass('selected');
            $(".goods__list").removeClass('list');
            $('.goods__lists').removeClass('selected');
            $('.goods__blocks').addClass('selected');
        });
    });

    /*- goods -*/
    $('.goods__lists').click(function () {
        var parent = $(this).parents('.goods');
        $('.goods__blocks', parent).removeClass('selected');
        $(this).addClass('selected');
        $(".goods__list").addClass('list');
    });
    $('.goods__blocks').click(function () {
        var parent = $(this).parents('.goods');
        $('.goods__lists', parent).removeClass('selected');
        $(this).addClass('selected');
        $('.goods__list').removeClass('list');
    });

    /*- promo-slider__inner -*/
    $(".promo-slider__inner").sliderkit({
        auto: true,
        autospeed: 5000,
        tabs: true,
        freeheight: true,
        circular: true,
        panelfx: "none"
    });

    /*- filter-goods__content .closed -*/
    $('.filter-goods__content .closed dt').click(function (e) {

        if ($(this).parent().hasClass('selected')) {
            $(this).parent().removeClass('selected');
        } else {
            $(this).parent().addClass('selected');
        }
    });

    /*- price -*/
    jQuery("#price").slider({
        min: 0,
        max: 100000,
        values: [0, 100000],
        range: true,
        stop: function (event, ui) {
            jQuery("#price__min-cost").val(jQuery("#price").slider("values", 0));
            jQuery("#price__max-cost").val(jQuery("#price").slider("values", 1));

        },
        slide: function (event, ui) {
            jQuery("#price__min-cost").val(jQuery("#price").slider("values", 0));
            jQuery("#price__max-cost").val(jQuery("#price").slider("values", 1));
        }
    });

    jQuery("input#price__min-cost").change(function () {

        var value1 = jQuery("#price__min-cost").val();
        var value2 = jQuery("#price__max-cost").val();

        if (parseInt(value1) > parseInt(value2)) {
            value1 = value2;
            jQuery("#price__min-cost").val(value1);
        }
        jQuery("#price").slider("values", 0, value1);
    });


    jQuery("#price__max-cost").change(function () {

        var value1 = jQuery("#price__min-cost").val();
        var value2 = jQuery("#price__max-cost").val();

        if (value2 > 100000) {
            value2 = 100000;
            jQuery("input#price__max-cost").val(100000)
        }

        if (parseInt(value1) > parseInt(value2)) {
            value2 = value1;
            jQuery("#price__max-cost").val(value2);
        }
        jQuery("#price").slider("values", 1, value2);
    });

    jQuery('#price input').keypress(function (event) {
        var key, keyChar;
        if (!event)
            var event = window.event;

        if (event.keyCode)
            key = event.keyCode;
        else if (event.which)
            key = event.which;

        if (key == null || key == 0 || key == 8 || key == 13 || key == 9 || key == 46 || key == 37 || key == 39)
            return true;
        keyChar = String.fromCharCode(key);

        if (!/\d/.test(keyChar))
            return false;

    });

    /*- b-core-ui-select__select -*/
    $(window).load(function () {

        $('.b-core-ui-select__select').coreUISelect({
            onInit: addCoreUISelectListener,
            onOpen: addCoreUISelectListener,
            onClose: addCoreUISelectListener,
            onChange: addCoreUISelectListener,
            onDestroy: addCoreUISelectListener
        });

        function addCoreUISelectListener(select, event) {
            console.log(select, event);
        }

    });

    /*- vacancies -*/
    $('.vacancies__link').click(function (e) {

        if ($(this).parent().hasClass('selected')) {
            $(this).parent().removeClass('selected');
        } else {
            $(this).parent().addClass('selected');
        }
    });

    /*- popup -*/
    var popupParams, popupSelect, docHeight, citySelect, mapCanvas, mapLatlng, markerTitle, infoWindowContent, popupTitle, gmapCords, radioSelected;

    $('.show-popup').click(function () {
        popupParams = $(this).attr('href');
        popupSelect = $(popupParams);
        getPopup('show', this);
        return false;
    });

    $('body').on('click', '.msg-box', function () {
        $('#successfully').remove();
    });

    $('body').on('click', '.global-popup__close, .global-popup__popup-overlay', function () {
        getPopup('hide', this);
        return false;
    });

    function getPopup(action, el) {
        if (action == 'show') {
            popupSelect.fadeIn(100);
        } else {
            popupSelect.fadeOut(100);
        }

    }

    /*- product-info__slider -*/
    $(".product-info__slider").sliderkit({
        shownavitems: 3,
        circular: true,
        navitemshover: false,
        panelfxspeed: 400,
        auto: false,
        autostill: false
    });

    /*- scroll-simple -*/
    $('.scroll-simple').scrollbar({
        "type": "simple"
    });
    $('#total-p').html(totalPrice() + '<span class="currency">i</span>');
    $(function () {
        $('.social-tabs__title').click(function () {
            $(this)
                    .siblings().removeClass('selected').end()
                    .next('.social-tabs__content').andSelf().addClass('selected');
        });
    });

    function totalPrice() {
        if ($.cookie('basket')) {
            var data = JSON.parse($.cookie('basket'));
            var t = 0;
            for (var i = 0; i < data.rows.length; i++) {
                if (data.rows[i] != null)
                    t += parseInt(data.rows[i]['price']) * parseInt(data.rows[i]['quantity']);
            }
            return t;
        } else
            return false;
    }

    function removeFromBasket(id) {
        if ($.cookie('basket')) {
            var data = JSON.parse($.cookie('basket'));
            for (var i = 0; i < data.rows.length; i++) {
                if (data.rows[i] != null && data.rows[i]['id'] == id)
                    delete data.rows[i];
            }
            $.cookie("basket", JSON.stringify(data), {expires: 31, path: '/'});
        }
    }

    function removeFromBasketSingle(id, c) {
        if ($.cookie('basket')) {
            var data = JSON.parse($.cookie('basket'));
            var total = 0;
            for (var i = 0; i < data.rows.length; i++) {
                if (data.rows[i] != null && data.rows[i]['id'] == id) {
                    total = parseInt(data.rows[i]['quantity']) - parseInt(c);
                    if (total <= 0)
                        delete data.rows[i];
                    else
                        data.rows[i]['quantity'] = total;
                }

            }
            $.cookie("basket", JSON.stringify(data), {expires: 31, path: '/'});
        }
    }

    $('body').on('click', '.shopping-cart__goods__list__counter .number__counter .number__counter__more', function () {
        var prod_id = $(this).parents('ul').find('.shopping-cart__goods__list__delete a').data('id');
        var prod_title = $(this).parents('ul').find('.shopping-cart__goods__list__title h3 a').text();
        var prod_price = $(this).data('price');
        var prod_url = $(this).data('url');
        var prod_image = $(this).data('image');
        var prod_t = $(this).data('t');
        addProduct(prod_id, prod_title, prod_price, prod_url, prod_image, prod_t);
        showBasket();
    });

    $('body').on('click', '.add-f-b', function () {
        var prod_id = $(this).parents('tr').find('td:last-child a').data('id');
        var prod_title = $(this).parents('tr').find('td:nth-child(2) a').text();
        var prod_price = parseFloat($(this).parents('tr').find('td:nth-child(3) span').text());
        var prod_url = $(this).parents('tr').find('td:nth-child(2) a').attr('href');
        prod_url = prod_url.replace('/product', 'product');
        var prod_image = $(this).parents('tr').find('td:nth-child(1) a img').attr('src');
        prod_image = prod_image.replace('/images/articles/', '');
        var prod_t = $(this).parents('tr').find('td:nth-child(4) div').find('input').data('t');
        addProduct(prod_id, prod_title, prod_price, prod_url, prod_image, prod_t);
        showBasket();
        var prodTotalPrice = parseFloat($(this).parents('tr').find('td:nth-child(5) span').text());
        var p = (parseFloat(prodTotalPrice) + parseFloat(prod_price));
        if (p <= prod_t * prod_price)
            $(this).parents('tr').find('td:nth-child(5) span').html(p + '<span class="currency">c</span>');
        $('#total-p').html(totalPrice() + '<span class="currency">i</span>');
    });

    $('body').on('click', '.global-table__delete', function () {
        var id = $(this).data('id');
        removeFromBasket(id);
        $(this).parents('tr').remove();
        showBasket();
    });

    $('body').on('click', '.shopping-cart__goods__list__counter .number__counter .number__counter__fewer', function () {
        var id = $(this).parents('ul').find('.shopping-cart__goods__list__delete a').data('id');
        removeFromBasketSingle(id, 1);
        showBasket();
    });

    $('body').on('click', '.remove-f-b', function () {
        var prod_t = $(this).parents('tr').find('td:nth-child(4) div').find('input').val();
        if (parseInt(prod_t) >= 1) {
            var id = $(this).parents('tr').find('td:last-child a').data('id');
            var prod_price = parseFloat($(this).parents('tr').find('td:nth-child(3) span').text());
            removeFromBasketSingle(id, 1);
            showBasket();
            var prodTotalPrice = parseFloat($(this).parents('tr').find('td:nth-child(5) span').text());
            var p = (parseFloat(prodTotalPrice) - parseFloat(prod_price));
            if (p > 0)
                $(this).parents('tr').find('td:nth-child(5) span').html(p + '<span class="currency">c</span>');
            $('#total-p').html(totalPrice() + '<span class="currency">i</span>');
        }
    });

    $('body').on('click', '.shopping-cart__goods__list__delete a', function () {
        var id = $(this).data('id');
        removeFromBasket(id);
        showBasket();
    });

    function isEmptyBasket() {
        if (!$.cookie('basket') || $('.shopping-cart__goods__list li').length == 0) {
            $('.shopping-cart__goods__inner .green-button').hide();
            $('#total').hide();
            $('.shopping-cart__goods__inner div div').html('<span id="hint" style="float: left;">Ваша корзина пуста, пожалуйста добавьте товары</span>');
            return false;
        }
    }

    function productsCount() {
        if ($.cookie('basket')) {
            var items = JSON.parse($.cookie("basket"));
            var totalCount = 0;
            for (var i = 0; i < items.rows.length; i++) {
                if (items.rows[i] != null) {
                    totalCount += parseInt(items.rows[i]['quantity']);
                }
            }
            if (totalCount > 0)
                return totalCount;
            else
                return false;
        } else
            return false;
    }

    function checkCount(id) {
        if ($.cookie('basket')) {
            var items = JSON.parse($.cookie("basket"));
            var totalCount = 0;
            for (var i = 0; i < items.rows.length; i++) {
                if (items.rows[i] != null && items.rows[i]['id'] == id) {
                    totalCount = parseInt(items.rows[i]['quantity']);
                }
            }
            return totalCount;

        } else
            return false;
    }

    if (productsCount()) {
        $('.badge').text(productsCount());
        $('.badge').show();
    }

    function showBasket() {
        isEmptyBasket();
        if (productsCount()) {
            $('.badge').text(productsCount());
            $('.badge').show();
        } else {
            $('.badge').hide();
        }
        if ($.cookie('basket')) {
            items = JSON.parse($.cookie("basket"));
            $('.shopping-cart__goods__inner .green-button').show();
            $('#total').show();
            var html = '<ul class="shopping-cart__goods__list">';
            var totalSum = 0;
            for (var i = 0; i < items.rows.length; i++)
            {
                if (items.rows[i] != null) {
                    totalSum += parseInt(items.rows[i]['price']) * parseInt(items.rows[i]['quantity']);
                    html += '<li class="shopping-cart__goods__list__item">' +
                            '<ul>' +
                            '<li class="shopping-cart__goods__list__title">' +
                            '<h3>' +
                            ' <a href="/' + items.rows[i]['url'] + '">' + items.rows[i]['name'] + '</a>' +
                            '</h3>' +
                            '</li>' +
                            '<li class="shopping-cart__goods__list__counter">' +
                            '<div class="number__counter">' +
                            '<div class="number__counter__fewer">' +
                            '<span>-</span>' +
                            '</div>' +
                            '<div class="number__counter__result">' +
                            '<input type="text" data-t="' + parseInt(items.rows[i]['t']) + '" value="' + items.rows[i]['quantity'] + '">' +
                            '</div>' +
                            '<div class="number__counter__more" data-t="' + parseInt(items.rows[i]['t']) + '" data-price="' + parseInt(items.rows[i]['price']) + '" data-url="' + parseInt(items.rows[i]['url']) + '" data-image="' + parseInt(items.rows[i]['image']) + '">' +
                            '<span>+</span>' +
                            '</div>' +
                            '</div>' +
                            '</li>' +
                            '<li class="shopping-cart__goods__list__price">' + numeral(parseInt(items.rows[i]['price']) * parseInt(items.rows[i]['quantity'])).format('0,0') + '<span>c</span></li>' +
                            '<li class="shopping-cart__goods__list__delete">' +
                            '<a href="#" data-id="' + items.rows[i]['id'] + '">Удалить</a>' +
                            '</li>' +
                            '</ul>' +
                            '</li>';
                }
            }
            html += '</ul>';
            $('.shopping-cart__goods__inner div div').html(html);
            $('#total i').text(totalSum);
        }
        isEmptyBasket();
    }

    var data = {"total": 0, "rows": []};
    var totalCost = 0;
    function addProduct(id, name, price, url, image, t) {
        if (checkCount(id) < t) {
            if ($.cookie('basket')) {
                var items = JSON.parse($.cookie("basket"));
                if (items.rows[0] != null)
                    data = JSON.parse($.cookie('basket'));
            }
            function add() {
                for (var i = 0; i < data.total; i++) {
                    if (items.rows[i] != null) {
                        var row = data.rows[i];
                        if (typeof row.id !== "undefined" && row.id == id) {
                            row.quantity += 1;
                            return;
                        }
                    }
                }
                data.total += 1;
                data.rows.push({
                    id: id,
                    quantity: 1,
                    price: price,
                    name: name,
                    url: url,
                    t: t,
                    image: image
                });
            }
            add();
            totalCost += price;
            $.cookie("basket", JSON.stringify(data), {expires: 31, path: '/'});
        }
    }

    $('.product-info__buy').on('click', function () {
        var prod_id = $(this).data('id');
        var prod_title = $(this).data('title');
        var prod_price = $(this).data('price');
        var prod_url = $(this).data('url');
        var prod_image = $(this).data('image');
        var prod_t = $(this).data('t');
        var cart = $('.shopping-cart__link');
        var prod_count = $(this).parents('ul').find('input').val();
        var imgtodrag = $('.sliderkit-panels div a').find("img").eq(0);
        if (imgtodrag) {
            var imgclone = imgtodrag.clone()
                    .offset({
                        top: imgtodrag.offset().top,
                        left: imgtodrag.offset().left
                    })
                    .css({
                        'opacity': '0.5',
                        'position': 'absolute',
                        'height': '150px',
                        'width': '150px',
                        'z-index': '100'
                    })
                    .appendTo($('body'))
                    .animate({
                        'top': cart.offset().top + 10,
                        'left': cart.offset().left + 10,
                        'width': 75,
                        'height': 75
                    }, 1000, 'easeInOutExpo');

            setTimeout(function () {
                for (var i = 0; i < prod_count; i++)
                    addProduct(prod_id, prod_title, prod_price, prod_url, prod_image, prod_t);
                showBasket();
                cart.effect("shake", {
                    times: 2
                }, 200);
            }, 1500);

            imgclone.animate({
                'width': 0,
                'height': 0
            }, function () {
                $(this).detach()
            });
        }
        return false;
    });

    $('.number__list').on('click', '.green-button', function () {
        var prod_id = $(this).data('id');
        var prod_title = $(this).data('title');
        var prod_price = $(this).data('price');
        var prod_url = $(this).data('url');
        var prod_image = $(this).data('image');
        var prod_t = $(this).data('t');
        var prod_count = $(this).parents('ul').find('input').val();
        var cart = $('.shopping-cart__link');
        var imgtodrag = $(this).parents('.goods-item__info').find("img").eq(0);
        if (imgtodrag) {
            var imgclone = imgtodrag.clone()
                    .offset({
                        top: imgtodrag.offset().top,
                        left: imgtodrag.offset().left
                    })
                    .css({
                        'opacity': '0.5',
                        'position': 'absolute',
                        'height': '150px',
                        'width': '150px',
                        'z-index': '100'
                    })
                    .appendTo($('body'))
                    .animate({
                        'top': cart.offset().top + 10,
                        'left': cart.offset().left + 10,
                        'width': 75,
                        'height': 75
                    }, 1000, 'easeInOutExpo');

            setTimeout(function () {
                for (var i = 0; i < prod_count; i++)
                    addProduct(prod_id, prod_title, prod_price, prod_url, prod_image, prod_t);
                showBasket();
                cart.effect("shake", {
                    times: 2
                }, 200);
            }, 1500);

            imgclone.animate({
                'width': 0,
                'height': 0
            }, function () {
                $(this).detach()
            });
        }
        return false;
    });

    $('.number__counter').on('click', '.number__counter__fewer', function () {
        var input = $(this).next().find('input');
        var value = input.val();
        if (parseInt(value) > 1) {
            input.val(parseInt(value) - 1);
        }
    });

    $('.number__counter').on('click', '.number__counter__more', function () {
        var input = $(this).prev().find('input');
        var value = input.val();
        if (parseInt(value) < parseInt(input.data('t'))) {
            input.val(parseInt(value) + 1);
        }
    });

    $('.search-form__type-text input').keyup(function (e) {
        var q = $(this).val();
        if (q.length >= 3) {
            if (request != null)
                request.abort();
            var request = $.ajax({
                url: "/ajax/search",
                cache: false,
                type: "POST",
                data: {q: q},
                dataType: "html"
            });
            request.done(function (resp) {
                var j = JSON.parse(resp);
                var html = '';
                $(document).keydown(
                        function (e) {
                            if (e.keyCode == 40) {
                                $('.search-form__type-text__list ul li:first').focus();
                            }
                        }
                );
                $.each(j, function (k, v)
                {
                    html += '<li tabindex="' + (k + 1) + '"><a href="/' + v.url + '" style="color: #000;">' + v.title + '</a> <span style="color: #A6A6A6;">(арт. ' + v.articul + ')</li>';
                });
                $('.search-form__type-text__list').show().children('ul').html(html);
                $('.search-form__type-text__list ul').on('focus', 'li', function () {
                    $this = $(this);

                    $this.addClass('active-f').siblings().removeClass();
                    $this.closest('.search-form__type-text__list').scrollTop($this.index() * $this.outerHeight());
                }).on('keydown', 'li', function (e) {
                    $this = $(this);
                    var sel = $('.search-form__type-text__list ul li:focus');
                    if (e.which == 13) {
                        window.location.href = sel.find('a').attr('href');
                    }
                    if (e.keyCode == 40) {
                        $this.next().focus();
                        return false;
                    } else if (e.keyCode == 38) {
                        $this.prev().focus();
                        return false;
                    }
                });
            });
            request.fail(function (jqXHR, textStatus) {
                alert("Request failed: " + textStatus);
            });
        }
    });
//    msgBox('Ваша покупка успешно добавлена.', ' Для её просмотра, перейдите в <strong>корзину</strong>');
    function msgBox(title, desc) {
        var html = '<div id="successfully" class="global-popup">' +
                '<div class="global-popup__description">' +
                '<div class="global-popup__description__inner">' +
                '<span class="global-popup__close msg-box">' +
                '<span>Закрыть</span>' +
                '</span>' +
                '<span class="successfully">' + title + '<br /> ' + desc + '</span>' +
                '</div>' +
                '</div>' +
                '<div class="global-popup__popup-overlay msg-box">&nbsp;</div>' +
                '</div>';
        $('body').append(html);
        $('#successfully').show();
    }
    jQuery(".masked-phone").mask("+7 (999) 999-99-99");

    $('.region-list li a').on('click', function () {
        var elem = $(this);
        var id = elem.data('id');
        $.post('/ajax/setRegion', {id: id}, function (resp) {
            resp == 'sucсess' ? window.location.reload() : msgBox('Ошибка', 'В данный момент Вы не сможете изменить Ваш регион, попробуйте позже.');
        });
    });
    var filter_xhr = null;
    $(".filter-goods [type=checkbox]").change(function () {
        $('#product_search').remove();
        var elem = $(this);
        var ids = '';
        $("input:checkbox[class=f-filter]:checked").each(function ()
        {
            ids += $(this).val() + '/';
        });
        ids = ids.substr(0, ids.length - 1);
        var brandID = $('input[name="brand"]').val();
        if (filter_xhr != null)
            filter_xhr.abort();
        if (ids.length > 0) {
            if (typeof brandID != 'undefined')
                ids += '/' + brandID;
            filter_xhr = $.post("/ajax/filter", {ids: ids}, function (cnt)
            {
                var html = '<div style="display: block;" id="product_search" class="search-result">' +
                        '<div class="search-result__corn">&nbsp;</div>' +
                        '<ul>' +
                        '<li>Найдено <i data-search-count="true">' + cnt + '</i> запчастей</li>' +
                        '<li style="display: block;">' +
                        '<a data-search-link="true" href="?types=' + ids + '">Показать</a>' +
                        '</li>' +
                        '</ul>' +
                        '</div>';
                elem.parent('.checkbox').append(html);
            });
        } else
            $('#product_search').hide();

        return false;
    });

    $('.center .green-button').on('click', function () {
        var elem = $(this);
        var id = elem.data('id');
        var type = elem.data('type');
        var data = {type: '', id: 0};
        data.type = type;
        data.id = id;
        $('.global-table tbody tr').removeClass('selected');
        elem.parents('tr').addClass('selected');
        $.cookie('sale', JSON.stringify(data), {expires: 31, path: '/'});
        return false;
    });

    $('.availability__indicator').mousemove(function (event) {
        var left = event.pageX - 65;
        var top = event.pageY - 50;
        var count = $(this).data('count');
        $('#serch-r-cnt').text('В наличии ' + count + ' шт.');
        $('.nal').css({top: top, left: left}).show();
    });
    $('.availability__indicator').mouseout(function () {
        $('.nal').hide();
    });

    $('#clearSearch').click(function () {
        $('input[name="q"]').val('');
        $('.search-form__type-text__list').hide();
        $(this).hide();
    });

});
function msgBox(title, desc) {
    var html = '<div id="successfully" class="global-popup">' +
            '<div class="global-popup__description">' +
            '<div class="global-popup__description__inner">' +
            '<span class="global-popup__close msg-box">' +
            '<span>Закрыть</span>' +
            '</span>' +
            '<span class="successfully">' + title + '<br /> ' + desc + '</span>' +
            '</div>' +
            '</div>' +
            '<div class="global-popup__popup-overlay msg-box">&nbsp;</div>' +
            '</div>';
    $('body').append(html);
    $('#successfully').show();
}